﻿using System;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;

namespace SopCastRecorder
{
	public class SopCastBody : SopCastBase
	{
		private static int AddressTextIndex = OptionFile.Option1.SopCastBodyAddressTextIndex;

		private IntPtr AddressTextHandle
		{
			get
			{
				return this.EditHandles[AddressTextIndex];
			}
		}
		public string AddressText
		{
			set
			{
				Win32Api.SetText2(this.AddressTextHandle, value);
			}
		}

		public static SopCastBody GetInstance(IntPtr[] hWnds)
		{
			for (var i = 0; i < hWnds.Length; i++)
			{
				var sopCastBody1 = SopCastBody.GetInstance(hWnds[i]);
				if (sopCastBody1 != null)
				{
					return sopCastBody1;
				}
			}
			return null;
		}
		private static SopCastBody GetInstance(IntPtr hWnd)
		{
			var body = new SopCastBody()
			{
				MainHandle = hWnd,
			};

			if (!body.CheckVisible())
			{
				return null;
			}

			if (!body.CheckCaption())
			{
				return null;
			}

			body.RefreshHandle();

			if (!body.CheckHandle())
			{
				return null;
			}
			return body;
		}
		protected override bool CheckCaption()
		{
			var s = Win32Api.GetWindowTextCS(this.MainHandle);
			if (Regex.IsMatch(s, OptionFile.Option1.NgCaptionRegex))
			{
				return false;
			}
			if (Regex.IsMatch(s, OptionFile.Option1.BodyCaptionRegex))
			{
				return true;
			}
			return false;
		}
		protected override bool CheckHandle()
		{
			if (this.EditHandles.Count() <= AddressTextIndex)
			{
				return false;
			}
			return true;
		}

		public void ClickGoButton()
		{
			var befores = Win32Api.GetHandles();
			Win32Api.Return(this.AddressTextHandle);
			while (true)
			{
				var newProcess = SopCast.GetNewProcess(befores);
				var sopCastPlayer1 = SopCastPlayer.GetInstance(newProcess, this);

				if (sopCastPlayer1 == null)
				{
					Thread.Sleep(100);
				}
				else
				{
					this.SopCast1.SopCastPlayer1 = sopCastPlayer1;
					this.SopCast1.SopCastPlayer1.SopCast1 = this.SopCast1;
					break;
				}
			}
		}

		public void Close()
		{
			new Thread(new ThreadStart(() =>
			{
				Win32Api.Close(this.MainHandle);
			})).Start();
		}
	}
}
